package com.xie.authority_system.config.security;

import com.xie.authority_system.entity.Permission;
import com.xie.authority_system.entity.User;
import com.xie.authority_system.service.PermissionService;
import com.xie.authority_system.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户认证处理类
 *
 * @author 谢金成
 * @date 2024/1/8 16:24
 */
@Component
public class CustomerUserDetailsService implements UserDetailsService {

    @Resource
    private UserService userService;

    @Resource
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户
        User user = userService.findUserByUserName(username);
        // 判断对象是否为空
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误!");
        }

        // 查询当前用户拥有的权限列表
        List<Permission> permissionList = permissionService.findPermissionListByUserId(user.getId());
        // 获取对应的权限编码
        List<String> codeList = permissionList.stream().filter(Objects::nonNull)
                .map(item -> item.getCode())
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        String[] strings = codeList.toArray(new String[codeList.size()]);
        // 设置权限列表
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(strings);
        user.setAuthorities(authorityList);
        // 设置该用户拥有的权限菜单
        user.setPermissionList(permissionList);
        return user;
    }
}
